package tour.spring.bc.dao.impl;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import tour.spring.bc.dao.AbstractDAO;

public class AbstractDAOImpl<E> implements AbstractDAO<E> {

	@PersistenceContext
	 private EntityManager entityManager;

    /** The entity class. */
    private final Class<E> entityClass;

    public AbstractDAOImpl(final Class<E> aEntityClass) {
        this.entityClass = aEntityClass;
    }

    @Override
    @Transactional
	public void save(E entity) {
		entityManager.merge(entity);
		
	}

	@Override
	public E load(long id) {
		return entityManager.find(entityClass, id);
	}

	@Override
	public void delete(E entity) {
		entityManager.detach(entity);
		
	}

	@Override
	public List<E> loadByNamedParams(String queryString, String[] paramNames,
			Object[] values) {
		Query query = entityManager.createQuery(queryString);
		for(int i=0; i<paramNames.length; i++) {
			query.setParameter(paramNames[i], values[i]);
		}
		return (List<E>) query.getResultList();
	}

	@Override
	public List<E> loadByNamedParam(String queryString, String paramName,
			Object value) {
		Query query = entityManager.createQuery(queryString);
		query.setParameter(paramName, value);
		return (List<E>) query.getResultList();
	}
	
	@Override
	public List<E> loadByNamedParam(String queryString, String paramName,
			Collection<?> values) {
		Query query = entityManager.createQuery(queryString);
		query.setParameter(paramName, values);
		return (List<E>) query.getResultList();
	}

	@Override
	public List<E> find(String queryString, Object[] values) {
		// TODO delete
		return null;
	}

	@Override
	public List<E> find(String queryString, Object value) {
		// TODO delete
		return null;
	}

	@Override
	public List<E> loadAll() {
		Query query=entityManager.createQuery("from " + entityClass.getName());
		return query.getResultList();
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public Class<E> getEntityClass() {
		return entityClass;
	}

	

}
